iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 28
0
AI & Machine Learning

ChatBot&Chatbase系列 第 28

Day28[Chatbase]Line->Chatbase

  • 分享至 

  • xImage
  •  

Day27已經做到可以使用python來發送訊息至Chatbase
接著就來整合到Line Chatbot!!!

我是使用Day27所製作的專案並加入之前已經做好的Line Chatbot
所以整合的部分是從步驟三開始!
步驟一步驟二是重複說明一下Line Chatbot&Chatbase的部分

1.安裝&引入套件
分為Chatbot的部分跟Chatbase的部分

  • Chatbot:就跟之前製作的一樣(包含聊天機器人需要的套件與爬蟲),可以參考Day21
from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import *

import requests 
from bs4 import BeautifulSoup
from urllib.request import urlretrieve
import random
  • Chatbase:連接Chatbase平台需要的(可以參考Day27)
from chatbase import Message

2.Chatbot與Webhook設定

app = Flask(__name__)

line_bot_api = LineBotApi('YOUR_LineBot_Channel access token')
handler = WebhookHandler('YOUR_LineBot_Channel secret')

@app.route("/", methods=['GET'])
def hello():
    return "Hello World!"

@app.route("/", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    print("Request body: " + body, "Signature: " + signature)
    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
       abort(400)

    return 'OK'

爬蟲(最新電影)

def movie():
    target_url = 'https://movies.yahoo.com.tw/'
    print('Start parsing movie ...')
    rs = requests.session()
    res = rs.get(target_url, verify=False)
    res.encoding = 'utf-8'
    soup = BeautifulSoup(res.text, 'html.parser')   
    content = ""
    for index, data in enumerate(soup.select('div.movielist_info h1 a')):
        if index == 20:
            return content
        print("data:")
        print(index)
        print(data)        
        title = data.text
        link =  data['href']
        content += '{}\n{}\n'.format(title, link)
    return content

3.整合!!!

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    msg = event.message.text
    #print(type(msg))
    msg = msg.encode('utf-8')
    if event.message.text == "最新電影":
    #加上傳送至Chatbase的程式
        chatbase_msg = Message(api_key="",
              type="user",
              platform="Line",
              version="1.0",
              user_id="",
              message=event.message.text,
              intent="movie"
              )
        resp =chatbase_msg.send()
        print(resp)
        a=movie()
        line_bot_api.reply_message(event.reply_token,TextSendMessage(text=a))
    if event.message.text == "你好":
    #加上傳送至Chatbase的程式
        chatbase_msg = Message(api_key="",
              type="user",
              platform="Line",
              version="1.0",
              user_id="",
              message=event.message.text,
              intent="Hello"
              )
        resp =chatbase_msg.send()
        print(resp)
        line_bot_api.reply_message(event.reply_token,TextSendMessage(text=event.message.text))

4.來看看結果!!!
傳送訊息仍然有回覆結果
https://ithelp.ithome.com.tw/upload/images/20180117/20107144ukLu929m7M.pnghttps://ithelp.ithome.com.tw/upload/images/20180117/20107144JWnR3yL7kn.png
同時在Chatbase也會收到訊息
User messages數量增加
https://ithelp.ithome.com.tw/upload/images/20180117/20107144ZrLLGZbvAy.png
因為沒有設定Not handled,所以訊息都會歸在Handled
(不過不知道為什麼最新電影是亂字碼)
https://ithelp.ithome.com.tw/upload/images/20180117/20107144LtlhGWuxTy.png


上一篇
Day27[Chatbase]QuickStart!Use Python!
下一篇
Day29[Chatbase]Facebook Message API
系列文
ChatBot&Chatbase30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言